package kael.aiur.util.string.impl;

import kael.aiur.exception.ParameterFormatException;
import kael.aiur.util.string.StringUtil;
import kael.aiur.util.string.SymmetricalSymbol;

public class StringUtilImpl implements StringUtil {
	private static final char SEPARATOR = '_';

	@Override
	public boolean isNull(String string) {
		if (string == null) {
			return true;
		}
		return false;
	}

	@Override
	public boolean isBlank(String string) {
		if (string == null || string.equals("")) {
			return true;
		}
		return false;
	}

	@Override
	public boolean isNotBlank(String string) {
		if (string != null && !string.equals("")) {
			return true;
		}
		return false;
	}

	@Override
	public String wrapArry(String wrapSymbol, String connectSymbol,
			String[] content) throws ParameterFormatException {
		if (wrapSymbol == null) {
			wrapSymbol = "()";
		}
		if (!SymmetricalSymbol.isWrapCouple(wrapSymbol)) {
			throw new ParameterFormatException("输入的包裹符号不是合法的包裹符号：" + wrapSymbol);
		}
		StringBuilder sb = new StringBuilder(wrapSymbol.charAt(0) + "");
		for (String str : content) {
			sb.append(str + connectSymbol);
		}
		sb.replace(sb.length() - 1, sb.length(), wrapSymbol.charAt(1) + "");
		return sb.toString();
	}

	@Override
	public String toUnderScoreCase(String s) {
		if (s == null) {
			return null;
		}
		StringBuilder sb = new StringBuilder();
		boolean upperCase = false;
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);

			boolean nextUpperCase = true;

			if (i < (s.length() - 1)) {
				nextUpperCase = Character.isUpperCase(s.charAt(i + 1));
			}

			if ((i > 0) && Character.isUpperCase(c)) {
				if (!upperCase || !nextUpperCase) {
					sb.append(SEPARATOR);
				}
				upperCase = true;
			} else {
				upperCase = false;
			}

			sb.append(Character.toLowerCase(c));
		}

		return sb.toString();
	}

	@Override
	public String toCamelCase(String s) {
		if (s == null) {
			return null;
		}


		StringBuilder sb = new StringBuilder(s.length());
		boolean upperCase = false;
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);

			if (c == SEPARATOR) {
				upperCase = true;
			} else if (upperCase) {
				sb.append(Character.toUpperCase(c));
				upperCase = false;
			} else {
				sb.append(c);
			}
		}

		return sb.toString();
	}

	@Override
	public String toCapitalizeCamelCase(String s) {
		if (s == null) {
			return null;
		}
		s = toCamelCase(s);
		return s.substring(0, 1).toUpperCase() + s.substring(1);
	}
}
